package cn.cms.controller;

import cn.cms.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public abstract class AbstractController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 拷贝request中信息为分页组件信息
     *
     * @param request 请求信息
     * @return 转换后处理结果
     */
    public static Map<String, Object> getRequestMap(HttpServletRequest request) {
        Map<String, String[]> reqParamMap = request.getParameterMap();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        if (reqParamMap != null) {
            Iterator<String> it = reqParamMap.keySet().iterator();
            while (it.hasNext()) {
                String keyName = it.next();
                String[] listValue = reqParamMap.get(keyName);
                if (listValue.length == 1) {
                    paramMap.put(keyName, StringUtil.xssFilter(listValue[0]));
                } else {
                    for (int v = 0; v < listValue.length; v++) {
                        listValue[v] = StringUtil.xssFilter(listValue[v]);
                    }
                    paramMap.put(keyName, listValue);
                }
            }
        }
        return paramMap;
    }

    public JSONObject getQueryCondition(HttpServletRequest request) {
        Map<String, Object> paramMap = getRequestMap(request);
        JSONObject json = new JSONObject();
        if (paramMap != null) {
            json = JSONObject.parseObject(JSONObject.toJSONString(paramMap));
        }
        return json;
    }

    public String getDivId(HttpServletRequest request) {
        return request.getParameter("divId");
    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("http_client_ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        // 如果是多级代理，那么取第一个ip为客户ip
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
        }
        return ip;
    }

}
